<template>
  <div class="user-profile">
    <div class="profile-header">
      <div class="avatar-container">
        <el-avatar :size="100" :src="avatarUrl" @error="handleAvatarError">
          <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
        </el-avatar>
        <div class="upload-btn">
          <el-upload
            class="avatar-uploader"
            action="/api/userProfile/uploadAvatar"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <el-button size="small" type="primary">更换头像</el-button>
          </el-upload>
        </div>
      </div>
      <div class="user-info">
        <h2>{{ userInfo.nickname || '用户' }}</h2>
        <p class="signature">{{ profile.signature || '这个人很懒，什么都没有留下' }}</p>
      </div>
    </div>

    <el-tabs v-model="activeTab">
      <el-tab-pane label="基本资料" name="basic">
        <el-form :model="profile" ref="profileForm" label-width="100px" :rules="rules">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="profile.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
              <el-radio :label="0">保密</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="生日" prop="birthday">
            <el-date-picker
              v-model="profile.birthday"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>
          
          <el-form-item label="个性签名" prop="signature">
            <el-input
              type="textarea"
              :rows="3"
              placeholder="写一句话介绍自己"
              v-model="profile.signature">
            </el-input>
          </el-form-item>
          
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="profile.phone" placeholder="请输入联系电话"></el-input>
          </el-form-item>
          
          <el-form-item label="收货地址" prop="deliveryAddress">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入详细收货地址"
              v-model="profile.deliveryAddress">
            </el-input>
          </el-form-item>
          
          <el-form-item label="紧急联系人" prop="emergencyContact">
            <el-input v-model="profile.emergencyContact" placeholder="请输入紧急联系人"></el-input>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="saveProfile">保存</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      
      <el-tab-pane label="维修记录" name="repairs">
        <div class="empty-data" v-if="!repairRecords.length">
          <el-empty description="暂无维修记录"></el-empty>
        </div>
        <div v-else class="repair-list">
          <el-timeline>
            <el-timeline-item
              v-for="(record, index) in repairRecords"
              :key="index"
              :timestamp="record.repairDate"
              :type="getStatusType(record.statusCode)">
              <el-card>
                <h4>{{ record.repairType }}</h4>
                <p>订单号: {{ record.orderId }}</p>
                <p>状态: {{ getStatusText(record.statusCode) }}</p>
                <p>地址: {{ record.repairAddress }}</p>
                <el-button 
                  size="small" 
                  type="primary" 
                  v-if="record.statusCode === 'WAIT_PAY'"
                  @click="handlePayment(record)">
                  去支付
                </el-button>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'UserProfile',
  data() {
    return {
      activeTab: 'basic',
      profile: {
        openid: '',
        avatar: '',
        gender: 0,
        birthday: '',
        signature: '',
        deliveryAddress: '',
        preferences: null,
        emergencyContact: '',
        phone: '',
      },
      userInfo: {
        nickname: '',
        username: '',
      },
      rules: {
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
      },
      repairRecords: [],
      avatarUrl: '',
    };
  },
  created() {
    this.getUserProfile();
    this.getUserInfo();
    this.getRepairRecords();
  },
  methods: {
    async getUserProfile() {
      try {
        const res = await axios.get('/api/userProfile/getUserProfile');
        if (res.data && res.data.code === 200) {
          this.profile = res.data.data;
          this.avatarUrl = this.profile.avatar || '';
        } else {
          this.$message.error('获取个人资料失败');
        }
      } catch (error) {
        console.error('获取个人资料失败', error);
        this.$message.error('获取个人资料失败');
      }
    },
    async getUserInfo() {
      try {
        const res = await axios.get('/api/user/getUserInfo');
        if (res.data && res.data.code === 200) {
          this.userInfo = res.data.data;
        }
      } catch (error) {
        console.error('获取用户信息失败', error);
      }
    },
    async getRepairRecords() {
      try {
        const res = await axios.get('/api/userHome/queryUserOrderRecord');
        if (res.data && res.data.code === 200) {
          this.repairRecords = res.data.data.orderFormEntityList || [];
        }
      } catch (error) {
        console.error('获取维修记录失败', error);
      }
    },
    async saveProfile() {
      try {
        this.$refs.profileForm.validate(async (valid) => {
          if (valid) {
            const res = await axios.post('/api/userProfile/updateProfile', this.profile);
            if (res.data && res.data.code === 200) {
              this.$message.success('个人资料更新成功');
            } else {
              this.$message.error(res.data.msg || '个人资料更新失败');
            }
          } else {
            return false;
          }
        });
      } catch (error) {
        console.error('保存个人资料失败', error);
        this.$message.error('保存个人资料失败');
      }
    },
    resetForm() {
      this.$refs.profileForm.resetFields();
      this.getUserProfile();
    },
    getStatusType(status) {
      const statusMap = {
        'TO_ACCEPT': 'warning',
        'HAVE_ACCEPTED': 'primary',
        'WAIT_PAY': 'danger',
        'HAVE_PAID': 'primary',
        'WAIT_FINISHED': 'primary',
        'HAVE_FINISHED': 'success',
        'REJECTED': 'info',
      };
      return statusMap[status] || 'info';
    },
    getStatusText(status) {
      const statusMap = {
        'TO_ACCEPT': '待受理',
        'HAVE_ACCEPTED': '已受理',
        'WAIT_PAY': '待支付',
        'HAVE_PAID': '已支付',
        'WAIT_FINISHED': '待完结',
        'HAVE_FINISHED': '已完结',
        'REJECTED': '已驳回',
      };
      return statusMap[status] || '未知状态';
    },
    handlePayment(record) {
      this.$router.push({
        path: '/payment',
        query: { orderId: record.orderId }
      });
    },
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        this.avatarUrl = res.data;
        this.profile.avatar = res.data;
        this.$message.success('头像上传成功');
      } else {
        // 静默处理头像上传失败，不显示错误信息
        console.log('头像上传失败:', res.msg);
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是JPG/PNG/WEBP格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过2MB!');
      }
      return isJPG && isLt2M;
    },
    handleAvatarError() {
      this.avatarUrl = '';
    }
  }
}
</script>

<style scoped>
.user-profile {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  min-height: 500px;
}

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.avatar-container {
  margin-right: 30px;
  text-align: center;
}

.upload-btn {
  margin-top: 10px;
}

.user-info {
  flex-grow: 1;
}

.signature {
  color: #606266;
  font-style: italic;
}

.repair-list {
  margin-top: 20px;
}

.el-tabs {
  margin-top: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}

.el-timeline-item {
  padding-bottom: 20px;
}
</style> 